/** @Date 下午4:43:22
  * @version 1.0.0
  * @author shangyd
  * Copyright (c) 2015
  */
package com.sdw.soft.test.zookeeper;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class SimulateClient {

	private static final Logger logger = LoggerFactory.getLogger(SimulateClient.class);
	
	protected ZooKeeper zk = null;
	private CountDownLatch countDown = new CountDownLatch(1);
	private static final int timeout = 5000;
	public static final String PATH = "/servers";
	public static final String PCHILDPATH = "server";
	
	public SimulateClient(String host,final String description) throws Exception{
		
		zk = new ZooKeeper(host, timeout, new Watcher(){
			@SuppressWarnings("static-access")
			@Override
			public void process(WatchedEvent event) {
				if(event.getState().SyncConnected == Event.KeeperState.SyncConnected){
					logger.info(description + " has conennected ... ...");
					countDown.countDown();
				}
			}
		});
	}
	
	public void createServer(String path,String data){
		try {
			zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void check(String path ,Watcher watcher) throws Exception {
		List<String> servers = zk.getChildren(PATH, null);
		Collections.sort(servers);
		if(servers.isEmpty()){
			logger.info("主server节点下 无子节点");
		}else{
			String first = servers.get(0);
			String data = new String(zk.getData(PATH+"/"+first, false, null));
			if(path.equals(data)){
				if(servers.size()==1){
					logger.info(path + " as the master start ... ..." + servers.toString());
				}else{
					logger.info("master down,slave auto switch ... ... at " + new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(new Date()));
				}
			}else{
				for(int i = 0;i < servers.size(); i++){
					String str = new String(zk.getData(PATH + "/" + servers.get(i), false, null));
					if(path.equals(str)){
						String watchNode = servers.get(i-1 );
						logger.info(path + " watch at node :" + watchNode);
						zk.exists(PATH+"/" + watchNode, watcher);
						break;
					}
					
				}
			}
		}
	}
	
	
	public void close(){
		try {
			zk.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
